import logging

from django.core.cache import cache
from django.http import JsonResponse
from django.views import View

from .models import Area
from xiaoyu_mall_new.utils.response_code import RETCODE

logger = logging.getLogger('django')


class AreasView(View):
    def get(self, request):
        area_id = request.GET.get('area_id')
        if not area_id:
            # 查省级数据
            # 先查缓存
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    province_model_list = Area.objects.filter(parent__isnull=True)
                    print(province_model_list)
                    province_list = []
                    for province_model in province_model_list:
                        province_list.append({'id': province_model.id, 'name': province_model.name})
                    # 使用过的数据，需要添加到缓存中
                    cache.set('province_list', province_list, 3600)
                    # return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'province_list': province_list})
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '省份数据有误'})

            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'province_list': province_list})
        else:
            #             查下一级的行政区划
            sub_data = cache.get('sub_data_'+area_id)
            print('缓存数据：',sub_data)
            if not sub_data:
                try:
                    parent_model = Area.objects.get(id=area_id)
                    sub_model_list = parent_model.subs.all()
                    print(sub_model_list)
                    sub_list = []

                    for sub_model in sub_model_list:
                        sub_list.append({'id': sub_model.id, 'name': sub_model.name})

                    sub_data = {'id': parent_model.id, 'name': parent_model.name, 'subs': sub_list}
                    cache.set('sub_data', sub_data, 3600)
                    # return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})
                except Exception as e:
                    logger.error(e)
                    return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '市区数据有误'})
            return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})